<template>
    <div class="h-table">
        <el-card v-if="props.data.length">
            <el-table :data="props.data" v-model="props.data" style="width: 100%; height: 100%;">
                <el-table-column v-for="(filed, index) in fields"
                    :width="formatFields.includes(filed.prop) ? '100' : 'auto'" :label="filed.label" :prop="filed.prop"
                    :key="index" />
                <el-table-column align="right" width="140">
                    <template #default="scope">
                        <el-button v-if="props.isShowEdit" size="small" @click="handleEdit(scope.$index, scope.row)">{{
                            props.editText }}</el-button>
                        <el-button v-if="props.isShowDelete" size="small" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">{{
                                props.deleteText
                            }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next" :page-size="props.pageSize" :total="props.total"
                @current-change="pageChangeHandle" />
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { IUserManagementState } from "@/store/models/Admin/UserManagement/types";
import { formatDateTime } from "@/utils/dayjs";
import { defineProps, getCurrentInstance, onMounted, ref, watch } from "vue";

interface IHTable {
    data: any[]
    propBlackList?: string[]
    isShowEdit?: boolean
    isShowDelete?: boolean
    editText?: string
    deleteText?: string
    fields: IUserManagementState['userFields']
    pageSize?: number
    total?: number
}
const props = withDefaults(defineProps<IHTable>(), {
    data: () => [],
    propBlackList: () => [],
    isShowEdit: true,
    isShowDelete: true,
    editText: "Edit",
    deleteText: "Delete",
    pageSize: 6,
})
const formatFields = ['createdAt', 'updatedAt']
const { emit } = getCurrentInstance()
const fields = ref(props.fields)

const pageChangeHandle = (page: number) => {
    emit("pageChangeHandle", page)
    setTimeout(() => {
        // 将页面滚动到底部
        window.scrollTo({
            top: document.body.scrollHeight,
            behavior: 'smooth'
        });
    }, 500);
}

const handleEdit = (index?: number, row?: any) => {
    emit("handleEdit", index, row)
}
const handleDelete = (index?: number, row?: any) => {
    emit("handleDelete", index, row)
}
onMounted(() => {
    setTimeout(() => {
        if (props.data.length) {
            if (!props.fields.length && props.propBlackList.length) {
                Object.keys(props.data[0])
                    .forEach(key => !props.propBlackList.includes(key) && fields.value.push({ label: key, prop: key }));
            }
        }
    }, 100)
})

</script>
<style lang="less" scoped>
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>

